import cv2
import numpy as np
import matplotlib.pyplot as plt
import pylab
 
def midsearch():
    img = cv2.imread("pic", -1)                                                   #导入图片，参数请自行修改
    h,w,c= img.shape
 
    mid=img[int(h*0.7):int(h),int(0.25*w):int(0.75*w)]                            #ROI选区，选择图像前面的一块区域
    hm, wm, cm = mid.shape  
    gray = cv2.cvtColor(mid, cv2.COLOR_BGR2GRAY)                                  #设置图像为灰度图
    ret, gray = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)  #大津法二值化
    gray = cv2.medianBlur(gray, 11)                                                #高斯滤波
    edges = cv2.Canny(gray, 50, 150, apertureSize=3)
    orgb = cv2.cvtColor(mid, cv2.COLOR_BGR2RGB)
    oShow = orgb.copy()
    lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 1, minLineLength=100, maxLineGap=60)#边缘检测之后霍夫变换得出直线
    fn=0
    n=0
    tan=1.0
    T=0.0
    for line in lines:
        x1, y1, x2, y2 = line[0]
        cv2.line(orgb, (x1, y1), (x2, y2), (255, 0, 0), 5)
        n+=2;
        fn+=x1
        fn+=x2
        if x1!=x2:
            tan=(y1-y2)/(x1-x2)
            if abs(tan)<0.1 and abs(x1-x2)>0.1*wm:
                    T+=1
        else:
            tan=1                                       #通过检测直线斜率检测是否遇到直角
    average=fn/n
    delta=average-wm/2
    # print(T)
    # print(delta)
    # print(average)
    # plt.subplot(121)
    # plt.imshow(oShow)
    # plt.axis('off')
    # plt.subplot(122)
    # plt.imshow(orgb)
    # plt.axis('off')
    # pylab.show()
    return delta,T
 
def midjudge(delta,T):
    #直角判断
    if delta>0 and T>=1:#右直角
        print("右直角")
    elif delta<0 and T>=1:#左直角
        print("左直角")
    else:
    #正常行驶，包括钝角以及圆弧的转弯
        if abs(delta)<=10:
            print("直行")
        elif delta>10:
            print("右转弯")
        elif delta<-10:
            print("左转弯")
 
 
delta,T=midsearch()
midjudge(delta,T)
cv2.waitKey(0)
cv2.destroyAllWindows()
